/****************************************************************************************
 *
 * 兼容所有赛事创建页面的公用混入
 *
 * *************************************************************************************/

import {
	apiStorageCurrency,
	tronAllowanceList, tronBalanceOfList,
	tronProposalThreshold,
	tronTokenAnalyze,
} from "@/views/uc/manage/js/manage.user.lib";
import { approve, hex2Num } from "@/libs/tron.lib";
import { objectAttrClear } from "@/libs/site.utils";
import { footContract, governancePoolContract } from "@/views/manage/js/manage.lib";
import { getEffectiveValueForContest3 } from "@/views/manage/js/manage.func";

export const mixinsVoteCreate = {
	/****************************************************************************************/
	data(){
		return {
			/*************************************简单值***********************************/
			submiting      : false,//提交中
			rateAmplify    : 1000,//P率放大倍数，可能由于区块链数据不能提交小数点？
			lockUpAmount   : '-',//发起投票需要质押票数
			betCoinSelected: 'USDT',//当前选择的币种
			betCoinInput   : 'TV94NeHgVQWvehzPULwKk6nHdN8LjSKLB9',//自定义输入的币种地址
			gameContract   : '',//玩法所在的合约，注意：是玩法
			gameServlet    : '',//游戏的接口名称
			/*************************************复杂值***********************************/
			/**(每个页面数据不同，这里只用于编辑器索引，各页面中重写覆盖)**/
			competitionSportsType:[],//体育类型
			competitionPlayType:[],//规则
			competitionPlayRule:{},//选中的玩法的规则，
			submitObject:{},//提交数据
			/**(每个页面数据不同，这里只用于编辑器索引，各页面中重写覆盖)**/
			
			//支持币种列表
			betCoinSupport:[
				{decimal: 6, name: "USDT", symbol: "USDT", address: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"},
				{decimal: 8, name: "XG", symbol: "XG", address: "TKbkX6nfmxdw7Vz56HxxuunZg1fdKUMtaM"},
				{decimal: 0, name: "自定支持幣種", symbol: "CUSTOM", address: ""}, //这里统一用CUSTOM,其它地方依赖这个字符
			],
			//当前准备要投注币种信息，默认usdt吧
			betCoinData: {
				decimal: 6,
				name    : "USDT",
				symbol  : "USDT",
				address : "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
			},
		}
	},
	created () {
		this.getVotePledge()//读取投票质押数,这个不依赖其它数据
		this.actSelectCoin(this.betCoinSelected) //选择默认的币种
	},
	methods:{
		
		//获取投票质押票数（可以独立运行）
		getVotePledge () {
			tronProposalThreshold(this.sender).then((res)=>{
				let lockUpAmount = hex2Num(res, this.xg.decimal)
				console.log('读取投票需要锁定的通证值是:',lockUpAmount)
				this.lockUpAmount = lockUpAmount
				if(isNaN(lockUpAmount)){//没有加载成功就递归
					setTimeout(() => {
						this.getVotePledge()
					},5000)
				}
			})
		},
		
		//先检查2种币是否授权，再检查余额，一种是基础币，一种是游戏币
		createProposal() {
			let sender = this.sender
			let that   = this
			//先查询授权情况(注意配对关系)
			this.inquiryApproveBatch(
				[that.xg.address, that.betCoinData.address],
				[governancePoolContract, footContract],
				[that.xg.decimal, that.betCoinData.decimal],
				[sender, sender],
				sender
			).then(function (rs) {
				//查看用户token余额，和USD余额，合约方法f会返回2数据,并堆成数组
				that.getUserBalanceBatch(
					[that.xg.address, that.betCoinData.address],
					[that.xg.decimal, that.betCoinData.decimal],
					sender
				).then(function (rs) {
					let userBalance = rs
					if (userBalance[0] < that.lockUpAmount) {
						that.$message.error('您的'+that.xg.name+'不足!')
						return
					}
					if (userBalance[1] < that.submitObject.totalBetL) {
						that.$message.error('您的'+that.betCoinData.name+'不足!')
						return
					}
					that.createProposalImpl()
				})
			})
		},
		
		//批量查询授权情况并执行授权
		inquiryApproveBatch(tokens, contracts, decimals, targetUser, sender) {
			return new Promise(function (resolve, reject) {
				tronAllowanceList(governancePoolContract, tokens, contracts, targetUser, sender, (res) => {
					let _analyzing = getEffectiveValueForContest3(res,2)
					let _counter = 0;
					console.log('用户授权余额', _analyzing)
					for (let i = 0; i < _analyzing.length; i++) {
						let owance = _analyzing[i] / Math.pow(10, decimals[i]);
						if (owance <= 0) {
							approve(contracts[i], tokens[i], sender, (res) => {
								_counter++;
								if (res == 1 && _counter == tokens.length){//每次成功并全部执行完，就resolve
									resolve();
								}
							});
						}else if (owance > 0) {
							_counter++;
						}
					}
					if (_counter == tokens.length) {
						resolve()
					}
				});
			})
		},
		
		/**
		 * 批量查询余额,其实就是返回授权额度，用这个值来判断，没有授权过就是0（支持多个币）
		 * @param tokens 币种数组，
		 * @param decimal 精度数组
		 * @param sender
		 * @returns 返回Promise.resolve(数组)
		 */
		getUserBalanceBatch(tokenArr, decimals, sender) {
			return new Promise(function (resolve, reject) {
				tronBalanceOfList(governancePoolContract, tokenArr, sender).then((res)=>{
					let _analyzing = getEffectiveValueForContest3(res,2)
					for (let i = 0; i < _analyzing.length; i++){
						_analyzing[i] = _analyzing[i] / Math.pow(10, decimals[i])
					}
					resolve(_analyzing);
				})
			})
		},
		
		/////////////////////////////////////////////////  其它交互处理 /////////////////////////////////////////////
		/////////////////////////////////////////////////  其它交互处理 /////////////////////////////////////////////
		/////////////////////////////////////////////////  其它交互处理 /////////////////////////////////////////////
		//选择自定义币种
		actSelectCoin (symbol) {
			this.betCoinSelected  = symbol
			//判断是现成的还是自定的
			if(symbol!='CUSTOM'){//如果不是自定义的，就直接赋值整个数据
				let _o = {...this.betCoinSupport.find((item)=> item.symbol == symbol)}
				this.betCoinData = _o //取到整个数据
			}else{//否则就清空，从链上读取币种数据
				this.betCoinData = objectAttrClear({...this.betCoinData}) //复制数据，然后清空属性
			}
		},
		
		//触发检测币种
		actGetCustomTokenInfo(){
			let _tempo = {...this.betCoinData} //复制对象
			this.betCoinData = objectAttrClear(_tempo) //清空之前选择的币种的数据
			this.getCustomTokenInfo() //加载自定久币种
		},
		
		//检测币种信息并读取 (独立为一个方法本来是为了，其它地方调用)
		getCustomTokenInfo(){
			this.$message.info('正在检查币种信息...');
			//解析币种，注意这里的o，是返回的币种信息对象
			tronTokenAnalyze(this.betCoinInput.trim(), this.sender, (o)=>{
				this.betCoinData = o
				apiStorageCurrency(o) //保存币种信息，用于前端显示
			})
		},
		
		//选择体育的时候
		actOnGameChange (value) {
			//取得体育数据
			let _gameData = this.competitionSportsType.find((item)=>item.gameTag == value)
			
			this.competitionPlayType    = _gameData.models //取得玩法数据
			this.gameServlet            = _gameData.servlet //设置servlet
			this.submitObject.groupType = _gameData.groupType //设置groupType
			this.submitObject.gameTag   = _gameData.gameTag //设置游戏标识
			//注意，如果是同一页面支持多个游戏选择，要清理下面方法中旧的玩法数据
		},
		
		//选择玩法的时候
		actOnPlayTypeChange(value){
			//取得玩法数据
			let _playData = this.competitionPlayType.find((item)=>item.playTag == value)
			console.log('选择的玩法:',value,',数据是',_playData)
			this.competitionPlayRule    = _playData.playRule //取得玩法的规则
			this.gameContract           = _playData.contract //设置合约
			this.submitObject.playTitle = _playData.playTitle // 设置玩法中文标题
			this.submitObject.playTag   = _playData.playTag // 设置玩法标识en
			this.submitObject.playType  = _playData.playType //设置玩法id
		}
	},
	
	////////////////////////////////////////////// 方法结束  ///////////////////////////////////////////////////////
	////////////////////////////////////////////// 方法结束  ///////////////////////////////////////////////////////
	////////////////////////////////////////////// 方法结束  ///////////////////////////////////////////////////////
	watch:{
		'submitObject.bet_max_amount': {
			handler (nv, ov) {
				// console.log('旧：',ov,'新：',nv)
				if(ov != nv){
					this.funcComputeJackpot()
				}
			},
			deep: false,
			immediate: true
		},
		'submitObject.bet_min_amount': {
			handler (nv, ov) {
				console.log('旧：',ov,'新：',nv)
				if(ov != nv){
					this.funcComputeJackpot()
				}
			},
			deep: false,
			immediate: true
		}
	},
}
